package com.sxbbc.common.basics.emails;

import org.apache.commons.lang3.StringUtils;

import com.function.common.GetRest;
import com.function.common.RestResponse;
import com.sxbbc.common.basics.enums.RandNumType;
import com.sxbbc.common.basics.service.SpringBeanFactoryUtils;
import com.sxbbc.common.basics.service.redis.RedisUtilsService;
import com.sxbbc.common.basics.utils.radoms.RandNumUtils;

public class SendMail {

    public static SendMail sendMail = null;

    public static SendMail getInstance() {
        if (sendMail == null) {
            synchronized (SendMail.class) {
                if (sendMail == null) {
                    sendMail = new SendMail();
                }
            }
        }
        return sendMail;
    }


    /**
     * * 发送验证码
     *
     * @param mail 接收方邮箱地址
     * @return
     */
    public RestResponse sendValid(String mail) {
        if (StringUtils.isBlank(mail)) {
            return GetRest.getFail("接收邮箱不能为空");
        }
        String validCode = RandNumUtils.getInstance().get(RandNumType.NUMBER, 6);
        //防止重复点击发送验证码
        String sendFlag = "sendflag_email_" + mail;
        boolean flag = getRedisUtilsService().setIncrSecond(sendFlag, 60);
        if (!flag) {
            return GetRest.getFail("您已发送验证码,请1分钟后重试");
        }
        String content = "您的验证码：" + validCode + ",本次操作验证码如下，请在10分钟内输入。如非本人操作，请忽略。";
        RestResponse result = MailUtils.getInstance().sendEmail(mail, content);
        if (result.isStatus()) {
            //保存验证码到缓存
            String key = "send_email_" + mail;
            getRedisUtilsService().setKey(key, validCode, 600);
        }
        return result;
    }

    /**
     * 校验验证码
     *
     * @param mail      邮箱
     * @param validCode 验证码
     * @return
     */
    public RestResponse validEmail(String mail, String validCode) {
        if (StringUtils.isEmpty(mail)) {
            return GetRest.getFail("未获取到邮箱");
        }
        if (StringUtils.isEmpty(validCode)) {
            return GetRest.getFail("请填写验证码");
        }
        //保存验证码到缓存
        String key = "send_email_" + mail;
        String val = getRedisUtilsService().getKey(key);
        if (StringUtils.isEmpty(val)) {
            return GetRest.getFail("验证码过期或已使用");
        }
        if (!val.equals(validCode)) {
            return GetRest.getFail("验证码不正确");
        }
        //校验成功后删除
        getRedisUtilsService().deleteKey(key);
        return GetRest.getSuccess("验证通过");
    }

    /**
     * 注入redis
     *
     * @return
     */
    private RedisUtilsService getRedisUtilsService() {
        return SpringBeanFactoryUtils.getApplicationContext().getBean(RedisUtilsService.class);
    }
}
